package com.qlc_demo_api.controller;

import com.qlc_demo_api.model.ResponseData;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class ExceptionController {

    // 捕捉shiro的异常
    @ExceptionHandler(ShiroException.class)
    public ResponseData handle401() {
        return ResponseData.noPermission().add("info", "您没有权限访问！");
    }

    // 捕捉其他异常
    @ExceptionHandler(Exception.class)
    public ResponseData globalException(HttpServletRequest request, Throwable ex) {
        int code = getStatus(request).value();
        return ResponseData.code(code).fail("访问出错，无法访问：" + ex.getMessage());
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
